

#include "CxType.h"
#include "CxGrabThread.h"


using namespace	 ImitateTansfer;

CxGrabThread::CxGrabThread(CxCapture *cap , CxWriteBuffer *buffer,size_t number):
                m_capture(cap),
				m_buffer(buffer),
				m_number(number),
				m_spin(true)
{
}

CxGrabThread::~CxGrabThread()
{
	boost::mutex::scoped_lock lock(m_mu);
    m_spin=false;
    if(m_capture!=NULL)
    {
        delete m_capture;
        m_capture=NULL;
    }

    m_thread.interrupt();
	cout<<"NO."<<m_number<<" GrabThread is join()....."<<endl;
    m_thread.join();
	cout<<"NO."<<m_number<<" GrabThread Have been exit....."<<endl;
}



void        CxGrabThread::SetFrame(double rate)
{
    CX_ASSERT(rate);
    boost::mutex::scoped_lock lock(m_mu);
    m_capture->SetFrameRate(rate);
}

bool		CxGrabThread::ChangeCapture(LPCSTR filename)
{
	try
	{
        boost::mutex::scoped_lock lock(m_mu);

		if(m_capture!=NULL)
		{
			delete m_capture;
		}

		m_capture=new ImpCxCapture(filename);
	}

	catch(boost::system::system_error &e)
	{
		CX_ERR_MESSAGE(e.what());
	}

    if(!m_capture->isOpened())
        return false;
    else return true;
}

void		CxGrabThread::ThreadFunc()
{

    cout<<"Grab thread id"<<boost::this_thread::get_id()<<endl;

	while(m_spin)
	{
		try
		{
			boost::this_thread::sleep(boost::posix_time::milliseconds(33));
			//Ã¿33ms·¢ËÍÒ»ÕÅÍ¼Æ¬

			if(m_capture==NULL || m_buffer==NULL)
				continue;
			else 
			{
				try
				{
					boost::mutex::scoped_lock lock(m_mu);

                    IplImage  *img=m_capture->GetFrame();   

					if(img!=NULL)
					{
						//Èç¹ûÍ¼ÏñÓÐÐ§·¢ËÍÍ¼Ïñ
						CxPackage *pack=CxPackage::Package(img->imageData,img->imageSize,
							img->height,img->width,img->depth);
						//Push Image
						m_buffer->PushBuffer(pack);
						cvReleaseImage(&img);
						sig_framecount(m_capture->GetFrameRate());

					}
					else 
					{
						delete m_capture;
						m_capture=NULL;
					}
				}
				//Òì³£´¦Àí
				catch(cv::Exception &e)
				{
					CX_ERR_MESSAGE(e.what());
				}
			}

            boost::this_thread::interruption_point();
		}
        //ÍË³öÒì³£´¦Àí
		catch(boost::thread_interrupted &)
		{

		}
	}

}
